package com.fanhang.samples.spring.sql2o.common;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.support.DaoSupport;

public class Sql2oDaoSupport extends DaoSupport {

	private Sql2oSession sql2oSession;
	
	private Sql2oSessionTemplate sessionTemplate;

	private boolean externalSqlSession = false;

	@Override
	protected void checkDaoConfig() throws IllegalArgumentException {
		if (this.sql2oSession == null) {
			throw new IllegalArgumentException("'sql2oSessionFactory' or 'sql2oSessionTemplate' is required");
		}
	}

	public void setSessionFactory(Sql2oSessionFactory sql2oSessionFactory) {
		if (!this.externalSqlSession) {
			
			this.sql2oSession = sql2oSessionFactory.openSession();
		}
	}
	
	public Sql2oSessionFactory getSessionFactory() {
		return null;
	}

	public Sql2oSessionTemplate getSessionTemplate() {
		return sessionTemplate;
	}

	public void setSessionTemplate(Sql2oSessionTemplate sessionTemplate) {
		this.sessionTemplate = sessionTemplate;
		this.externalSqlSession = true;
	}
	
	public void setDataSource(DataSource dataSource) {
		this.sql2oSession = new DefaultSql2oSession(dataSource);
	}

	public Sql2oSession getSql2oSession() {
		return this.sql2oSession;
	}
	
	@SuppressWarnings("unchecked")
	protected Map<String, ?> describe(Object model) {
		try {
			return BeanUtils.describe(model);
		} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			throw new DataAccessResourceFailureException(e.getMessage(), e);
		}
	}
}
